package com.ttbj.controller.notify;

import java.util.Map;
import java.util.SortedMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ttbj.constant.order.PayEnum;
import com.ttbj.controller.notify.paramHandler.ParamsHandler;
import com.ttbj.product.api.AppletUserFacade;
import com.ttbj.product.api.OrderFacade;
import com.ttbj.product.api.OriginalPayFacade;
import com.ttbj.product.bean.dto.OrderDto;
import com.ttbj.product.bean.dto.UserDto;

@Controller
@RequestMapping("/notity/original/app")
public class AppNotifyController {

	@Autowired
	OrderFacade orderFacade = null;

	@Autowired
	OriginalPayFacade originalPayFacade = null;

	@Autowired
	AppletUserFacade appletUserFacade = null;

	ParamsHandler handler = null;

	/**
	 * 原生微信预支付二维码获取
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/wx.do")
	@ResponseBody
	public void wxNotity(HttpServletRequest request, HttpServletResponse response) throws Exception {
		handler = new ParamsHandler();
		SortedMap<Object, Object> map = handler.weixinPayNotify(request, response);
		String orderId = (String) map.get("attach");
		String transaction_id = (String) map.get("transaction_id");
		String orderNum = (String) map.get("out_trade_no");
		String openId = getOpenId(orderId);
		originalPayFacade.payNotify(orderNum, openId, orderId, transaction_id,PayEnum.WX.getWay());
	}
	/**
	 * 原生支付宝预支付二维码获取
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/ali.do")
	@ResponseBody
	public void aliNotity(HttpServletRequest request, HttpServletResponse response) throws Exception {
		handler = new ParamsHandler();
		Map<String, String> map = handler.aliPayNotify(request, response);
		String orderId = map.get("body");
		String orderNum = map.get("out_trade_no");
		String transaction_id = map.get("trade_no");
		String openId = getOpenId(orderId);
		originalPayFacade.payNotify(orderNum, openId, orderId, transaction_id,PayEnum.ALI.getWay());
	}
 
	/*
	 *根据orderId中用户ID获取openId
	 */
	private String getOpenId(String orderId) throws Exception {
		String openId = null;
		if (orderId != null) {
			Long ordeId = Long.valueOf(orderId);
			OrderDto queryOrder = orderFacade.queryOrder(ordeId);
			if (queryOrder != null) {
				Long userId = queryOrder.getOrderWxUser();
				if (userId != null) {
					UserDto userDto = new UserDto();
					userDto.setId(userId);
					UserDto user = appletUserFacade.getUser(userDto);
					if (user != null) {
						openId = user.getOpenId();
					}
				}
			}
		}
		return openId;
	}

}
